<?php

namespace App\Models;

use App\Http\Controllers\LibApi\CqstLibController;
use App\Http\Controllers\LibApi\GshqLibController;
use App\Http\Controllers\LibApi\YzqLibApiController;
use App\Http\Controllers\QrCodeController;
use App\Http\Controllers\ScoreRuleController;
use Exception;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Support\Facades\DB;

/**
 * 用户微信信息
 * Class ArticleTypeModel
 * @package app\common\model
 */
class UserLibraryInfo extends BaseModel
{
    use HasFactory;

    const CREATED_AT = 'create_time';
    const UPDATED_AT = 'change_time';

    public $table = 'user_account_lib';

    /**
     * 根据account_id 获取读者证号
     */
    public function getAccountByAccountId($account_id)
    {
        $account = $this->where('id', $account_id)->value('account');
        if (empty($account)) {
            return false; //未绑定
        }
        return $account;
    }

    /**
     * 绑定读者证
     * @param 
     */
    public function add($data, $field = [])
    {
        $this->account = $data['cardnumber'];
        $this->username = $data['surname'];
        $this->password = $data['password'];
        $this->id_card = $data['IDcard'];
        $this->sex = $data['sex'] == 'F' ? 2 : 1;
        $this->tel = $data['phone'];
        $this->type = $this->getCardType($data['cardType']);
        $this->time = $data['dateenrolled'];
        $this->end_time = $data['datexpiry'];
        $this->pavilion = $data['branchname'];


        //获取注册积分
        $scoreRuleObj = new ScoreRuleController();
        $score_info = $scoreRuleObj->getScoreByType(1);
        if (!empty($score_info['score'])) {
            $this->score = $score_info['score'];
        }

        $this->save();

        if (!empty($score_info['score'])) {
            //添加积分推送信息
            $scoreRuleObj->addScoreLog([
                'account_id' => $this->id,
                'score' => $score_info['score'],
                'type_id' => 1,
                'type' => $score_info['type_name'],
                'intro' => $score_info['score'] > 0 ? '绑定读者证增加 ' . $score_info['score'] . ' 积分' :  '绑定读者证减少 ' . abs($score_info['score']) . ' 积分',
            ]);
        }

        return $score_info['score'];
    }

    /**
     * 修改绑定读者证
     * @param 
     */
    public function change($data, $res = null, $findWhere = [])
    {

        if ($data['lib_id'] == 2) {
            $cash = $data['cash'];
            $diff_money = $data['arrea'];

            $account = $data['reader_id'];
            $password = $data['password'];
            $username = $data['username'];
            //$resObj->cash = $res['realName'];
            $card = isset($data['id_card']) ? $data['id_card'] : null;
            $sex = $data['sex'];
            $tel = !empty($data['tel']) ? $data['tel'] : '';
            $type = $data['reader_type'];
            //$time = $data['createDateTime'];//测试环境
            $time = !empty($data['register_time']) ? $data['register_time'] : null; //正式环境
            $pavilion = $data['pavilion']; //正式环境
            $pavilion_note = $data['pavilion']; //正式环境
            //$resObj->diff_money = $res['realName'];//这个需要在请求一个接口
            //$resObj->is_surpass = $res['realName'];
            $end_time = !empty($data['validity_time']) ? $data['validity_time'] : null;
            $status_card = $data['status'];
        } else {
            $account = $data['cardno'];
            //获取读者证号信息
            $libapiObj = new YzqLibApiController();
            $readerInfo = $libapiObj->getReaderInfo($account);
            if ($readerInfo['code'] === 200) {
                $cash = $readerInfo['content']['readerFinInfo']['depositYuan'];
                $diff_money = $readerInfo['content']['readerFinInfo']['arrearsYuan'];
            }
            $password = $data['password'];
            $username = $data['realName'];
            //$resObj->cash = $res['realName'];
            $card = isset($data['idno']) ? $data['idno'] : null;
            $sex = $data['genderNote'] == '男' ? 1 : 2;
            $tel = !empty($data['mobile']) ? $data['mobile'] : '';
            $type = $data['cardTypeNote'];
            //$time = $data['createDateTime'];//测试环境
            $time = !empty($data['regDate']) ? $data['regDate'] : null; //正式环境
            $pavilion = $data['sublib']; //正式环境
            $pavilion_note = $data['sublibNote']; //正式环境
            //$resObj->diff_money = $res['realName'];//这个需要在请求一个接口
            //$resObj->is_surpass = $res['realName'];
            $end_time = $data['endDate'];
            $status_card = $data['statusNote'];
        }

        if (empty($res)) {
            $res = $this;

            //生成读者证二维码
            $qrCodeObj = new QrCodeController();
            $res->qr_url = $qrCodeObj->setQr($account, true);
        } elseif (empty($res['qr_url'])) {
            $qrCodeObj = new QrCodeController();
            $res->qr_url = $qrCodeObj->setQr($account, true);
        }
        $res->account = $account;
        $res->username = $username;
        $res->password = $password;
        $res->id_card = $card;
        $res->sex = $sex;
        $res->tel = $tel;
        $res->cash = $cash;
        $res->diff_money = $diff_money;
        $res->type = $type;
        $res->time = $time; //正式环境
        $res->end_time = $end_time;
        $res->pavilion = $pavilion; //正式环境
        $res->pavilion_note = $pavilion_note;
        $res->status_card = $status_card;

        $res->save();
        return $res->qr_url;
    }



    //判断读者证号密码是否正确 和是否绑定读者证
    public function checkAccountPwdIsNormal($user_id, $account_id = null)
    {
        if (empty($account_id)) {
            //获取用户当前信息
            $user_info = UserInfo::find($user_id);

            if (empty($user_info)) {
                throw new \Exception('用户信息获取失败');
            }
            if (empty($user_info['account_id'])) {
                throw new \Exception('该用户未绑定读者证号，请先绑定读者证');
            }

            $account_id = $user_info['account_id'];
        }

        $account_lib_info = UserLibraryInfo::find($account_id);
        if (empty($account_lib_info)) {
            throw new \Exception('读者证号获取失败，请稍后重试');
        }

        //判断读者证号的密码是否过期
        $libapiObj = new CqstLibController();
        $res = $libapiObj->login($account_lib_info->account, $account_lib_info->password);
        if ($res['code'] == 200) {
            $account_lib_info['account_id'] = $account_lib_info['id']; //多返回一个参数
            return $account_lib_info; //读者证号账号密码正确
        }
        throw new \Exception('读者证密码错误');
    }

    /**
     * 判断读者证是否被其他用户绑定
     */
    public function isBindAccount($account_id, $user_id = null)
    {
        $user_info = UserInfo::where('account_id', $account_id)->first();
        if ($user_info && $user_info['id'] != $user_id) {
            // $nickname = UserWechatInfo::where('id', $user_info['wechat_id'])->value('nickname');
            return '“' . $user_info['serial_number'] . '”已绑定此读者证号，请先解绑'; //未绑定
        }
        return true;
    }


    /**
     * 绑定已有读者证到此账号
     */
    public function bindExistsReader($user_id, $data)
    {
        //登录成功
        DB::beginTransaction();
        try {
            $result = $this->where('account', $data['account'])->first();
            if ($result) {
                $account_id = $result['id'];
                $qr_url = $result['qr_url'];
            } else {
                //生成读者证二维码
                $qrCodeObj = new QrCodeController();
                $this->qr_url = $qrCodeObj->setQr($data['account'], true);

                $this->account = $data['account'];
                $this->password = $data['password'];
                $this->username = $data['username'];
                $this->id_card = $data['card'];
                $this->cash = $data['cash'];
                $this->diff_money = $data['diff_money'];
                $this->sex = $data['sex'];
                $this->tel = $data['tel'];
                $this->type = $data['type'];
                $this->time = $data['time'];
                $this->end_time = $data['end_time'];
                $this->status_card = $data['status_card'];
                $this->save();
                $account_id = $this->id;
                $qr_url = $this->qr_url;
            }

            //判断是否有积分，如果有积分，同步在读者证上，之前遗留数据
            $userInfoModel = new UserInfo();
            $user_info_score = $userInfoModel->where('id', $user_id)->value('score');
            //修改读者证号二维码
            $userInfoModel->where('id', $user_id)->update([
                'account_id' => $account_id,
                'qr_url' => $qr_url,
                'score' => 0,
                'bind_time' => date('Y-m-d H:i:s')
            ]);

            if ($user_info_score) {
                //积分同步,增加积分
                $this->where('id', $account_id)->increment('score', $user_info_score);
            }

            //添加绑定日志
            $bindLogModel = new BindLog();
            $bindLogModel->add([
                'user_id' => $user_id,
                'account' => $data['account'],
                'password' => $data['password'],
                'state' => 1,
            ]);

            Db::commit();
            return true;
        } catch (\Exception $e) {
            Db::rollback();
            return false;
        }
    }
}
